<template>
  <Card class="!mt-10px">
    <Form ref="formRef" :model="attr" :rules="rules">
      <FormItem label="属性名" name="attrName" :label-col="{ span: 2 }" :wrapper-col="{ span: 4 }">
        <Input placeholder="请输入属性名" v-model:value="attr.attrName" />
      </FormItem>

      <FormItem name="attrValueList">
        <Button type="primary" :disabled="!attr.attrName" @click="addAttrValue">
          <template #icon><PlusOutlined /></template>
          添加属性值
        </Button>

        <Table
          class="mt-15px"
          :columns="columns"
          :data-source="attr.attrValueList"
          bordered
          :pagination="false"
          rowKey="id"
        >
          <template #bodyCell="{ column, index, record, text }">
            <template v-if="column.dataIndex === 'operator'">
              <Popconfirm
                :title="`您确认要删除 ${record.valueName} 数据吗？`"
                @confirm="delAttrValue(index)"
              >
                <template #icon><QuestionCircleOutlined style="color: red" /></template>
                <Button danger>
                  <template #icon><DeleteOutlined /></template>
                </Button>
              </Popconfirm>
            </template>
            <template v-if="column.dataIndex === 'id'">
              {{ index + 1 }}
            </template>
            <template v-if="column.dataIndex === 'valueName'">
              <!-- 
                两种模式切换显示
                实现：给每行数据添加一个标识 isShowEdit
              -->
              <!-- 编辑模式 -->
              <!-- 
                新的ref语法：将多个元素添加到一个ref中
               -->
              <Input
                placeholder="请输入属性值名称"
                :ref="(input: HTMLInputElement) => (inputsRef[index] = input)"
                v-if="record.isShowEdit"
                v-model:value="record.valueName"
                @blur="showDisplay(record, index)"
              />
              <!-- 显示模式 -->
              <div v-else @click="showEdit(record, index)">{{ text }}</div>
            </template>
          </template>
        </Table>
      </FormItem>

      <FormItem>
        <Button type="primary" class="mr-10px" @click="submit">确定</Button>
        <Button @click="cancel">取消</Button>
      </FormItem>
    </Form>
  </Card>
</template>

<script lang="ts">
  import { defineComponent } from 'vue';

  export default defineComponent({
    name: 'SaveOrUpdateAttr',
  });
</script>

<script lang="ts" setup>
  import { reactive, ref, nextTick } from 'vue';
  import { Card, Button, Form, FormItem, Input, Table, Popconfirm, message } from 'ant-design-vue';
  import { PlusOutlined, DeleteOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue';
  import { useCategoryStore } from '/@/store/modules/category';
  import { saveOrUpdateAttrApi } from '/@/api/product/attr';
  import type { SaveAttrModel, AttrValueModel, AttrModel } from '/@/api/product/model/attrModel';
  // 声明接受自定义事件
  const emit = defineEmits(['setIsShowAttrList']);
  const props = defineProps<{
    currentAttr: AttrModel;
  }>();

  const categoryStore = useCategoryStore();

  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      width: 80,
      align: 'center',
    },
    {
      title: '属性值名称',
      dataIndex: 'valueName',
    },
    {
      title: '操作',
      dataIndex: 'operator',
      width: 150,
    },
  ];

  const formRef = ref();
  const inputsRef = ref<HTMLInputElement[]>([]);

  const attr = reactive<SaveAttrModel>({
    attrName: props.currentAttr.attrName,
    attrValueList: props.currentAttr.attrValueList,
  });

  const rules = {
    attrName: [{ required: true, message: '请输入属性名', trigger: 'blur' }],
    attrValueList: [
      {
        required: true,
        message: '请至少添加一个属性值',
        type: 'array',
      },
    ],
  };

  // 提交表单
  const submit = async () => {
    await formRef.value.validate();

    const { id } = props.currentAttr;
    const { attrName, attrValueList } = attr;
    const { category3Id } = categoryStore;

    await saveOrUpdateAttrApi({
      id,
      attrValueList,
      attrName,
      categoryId: category3Id as number,
      categoryLevel: 3,
    });

    message.success(`${id ? '更新' : '添加'}属性成功`);

    cancel(); // 返回AttrList组件
  };

  // 点击添加属性值按钮触发回调
  // 让表格新增一行数据
  const addAttrValue = async () => {
    attr.attrValueList.push({
      valueName: '',
      // 添加用来切换模式的标识
      isShowEdit: true, // 因为一上来希望是编辑模式
    });
    // 页面更新是异步的
    await nextTick();
    // 让最后一个Input聚焦
    inputsRef.value[inputsRef.value.length - 1].focus();
  };

  // 切换到编辑模式
  const showEdit = async (record: AttrValueModel, index: number) => {
    record.isShowEdit = true;
    // 页面更新是异步的
    await nextTick();
    // 让Input聚焦
    inputsRef.value[index].focus();
  };

  // 切换到显示模式
  const showDisplay = (record: AttrValueModel, index: number) => {
    if (!record.valueName) {
      // 删除当前行数据
      attr.attrValueList.splice(index, 1);
      return;
    }

    record.isShowEdit = false;
  };

  // 删除属性值
  const delAttrValue = (index: number) => {
    attr.attrValueList.splice(index, 1);
    // 也要删除对应DOM元素，否则值为空，下次添加最后一个就不对了
    inputsRef.value.splice(index, 1);
  };

  const cancel = () => {
    emit('setIsShowAttrList');
  };
</script>
